const { logError } = require('../func/util')
const answersRawData = require('../mapping/answers-raw-data')
const manageAllSurveys = require('../mapping/manage-all-surveys')
const surveysRawData = require('../mapping/surveys-raw-data')

function collectAnswer(req, res) {
    try {
        const oneAnswer = req.body
        oneAnswer.id =
            answersRawData.getSpecifyAnswerId(oneAnswer.survey_id) + ''
        oneAnswer.collect_time = new Date().getTime() + ''
        answersRawData.addAnswer(oneAnswer)

        res.status(200)
        res.send({ msg: 'success' })
    } catch (error) {
        logError(error)
        res.status(500)
        res.send({ msg: '服务器出现未知异常' })
    }
}

function getSurvey(req, res) {
    try {
        const id = req.params.id
        const surveys = manageAllSurveys.get()
        const i = surveys.findIndex(s => s.id === id)

        if (i === -1) throw new NotFindIndexError('问卷不存在')
        if (surveys[i].delete) throw new NotFindIndexError('问卷已被删除')
        if (surveys[i].over) throw new NotFindIndexError('问卷已停止回收')

        res.status(200)
        res.send({
            data: surveysRawData.getSurvey(surveys[i].id),
            msg: 'success',
        })
    } catch (error) {
        if (error instanceof NotFindIndexError) {
            res.status(404)
            res.send({ msg: error.message })
            return
        }
        res.status(500)
        res.send({ msg: '服务器出现未知错误' })
    }
}

module.exports = {
    collectAnswer,
    getSurvey,
}
